package com.las.bot.cmd.group;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.las.annotation.BotCmd;
import com.las.bot.dao.CqMsgDao;
import com.las.cmd.BaseCommand;
import com.las.common.Constant;
import com.las.utils.mirai.CmdUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@BotCmd(funName = "群排行")
public class MsgTopCmd extends BaseCommand {

    private static Logger logger = LoggerFactory.getLogger(MsgTopCmd.class);

    @Autowired
    private CqMsgDao cqMsgDao;


    public MsgTopCmd() {
        super("发言统计", "发言排行","我的发言");
    }

    @Override
    public void execute(Long userId, Long id, Integer type, String command, ArrayList<String> args) throws Exception {
        if (type != Constant.MESSAGE_TYPE_GROUP) {
            return;
        }
        List<JSONObject> topList = cqMsgDao.findTop(id);
        if (CollectionUtil.isNotEmpty(topList)) {
            StringBuilder sb = new StringBuilder();
            sb.append("本周发言排行前三名：\n");
            int rand = 0;
            for (int i = 0; i < topList.size(); i++) {
                JSONObject object = topList.get(i);
                long qq = object.getLong("user_id");
                long count = object.getLong("total");
                if (userId.equals(qq)) {
                    rand = i + 1;
                }
                if (i < 3) {
                    sb.append("QQ：").append(qq).append("，发言：").append(count).append("次\n");
                }
            }
            if (rand > 0) {
                List<JSONObject> myList = topList.stream().filter(jsonObject -> userId.equals(jsonObject.getLong("user_id"))).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(myList)) {
                    JSONObject myObj = myList.get(0);
                    long count = myObj.getLong("total");
                    sb.append("\n本周您的发言：").append(count).append("次，排行第 ").append(rand).append(" 名");
                }
            } else {
                sb.append("\n本周您还未冒泡过！暂无排名");
            }
            CmdUtil.sendAtMessage(sb.toString(), userId, userId, id, type);
        } else {
            CmdUtil.sendMessage("暂无数据", userId, id, type);
        }
    }


}
